#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/components/generic/apis/cmsi/send_mp_weixin.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import datetime, base64
from django import forms
from components.component import Component, SetupConfMixin
from common.forms import BaseComponentForm, ListField, TypeCheckField, DefaultBooleanField
from .toolkit import configs

class SendMpWeixin(Component, SetupConfMixin):
    """
    apiLabel 发送公众号微信消息
    apiMethod POST
    
    ### 功能描述
    
    发送公众号微信消息
    
    ### 请求参数
    
    {{ common_args_desc }}
    
    #### 接口参数
    
    | 字段               |  类型      | 必选   |  描述      |
    |--------------------|------------|--------|------------|
    | receiver           |  string    | 是     | 微信接收者，包含绑定在指定公众号上的微信用户的 openid，多个以逗号分隔 |
    | data               |  dict      | 是     | 消息内容 |
    
    #### data 参数包含内容
    
    | 字段               |  类型      | 必选   |  描述      |
    |--------------------|------------|--------|------------|
    | heading            |  string    | 是     | 通知头部文字 |
    | message            |  string    | 是     | 通知文字 |
    | date               |  string    | 否     | 通知发送时间，默认为当前时间 "YYYY-mm-dd HH:MM" |
    | remark             |  string    | 否     | 通知尾部文字 |
    | is_message_base64  |  bool      | 否     | 通知文字message是否base64编码，默认False，不编码，若编码请使用base64.b64encode方法 |
    
    ### 请求参数示例
    
    ```python
    {
        "app_code": "esb_test",
        "app_secret": "xxx",
        "bk_token": "xxx",
        "receiver": "xxx",
        "data": {
            "heading": "蓝鲸平台通知",
            "message": "This 是 a test.",
            "date": "2017-02-22 15:36",
            "remark": "zhen 是一个测试！"
        }
    }
    ```
    
    ### 返回结果示例
    
    ```python
    {
        "result": true,
        "code": "00",
        "message": "微信消息发送成功。",
    }
    ```
    """
    sys_name = configs.SYSTEM_NAME

    class Form(BaseComponentForm):
        receiver = ListField(label=u'接收者', required=True)
        data = TypeCheckField(label=u'消息数据', promise_type=dict, required=True)

        def clean(self):
            data = self.cleaned_data
            return {'touser': data['receiver'],
               'data': SendMpWeixin.DataForm(data['data']).get_cleaned_data_or_error()
               }

    class DataForm(BaseComponentForm):
        heading = forms.CharField(label=u'通知头部文字', required=True)
        message = forms.CharField(label=u'通知文字', required=True)
        date = forms.CharField(label=u'通知发送时间', required=False)
        remark = forms.CharField(label=u'通知尾部文字', required=False)
        is_message_base64 = DefaultBooleanField(label=u'通知文字是否base64编码', default=False, required=False)

        def decode_message(self, message, is_message_base64):
            if is_message_base64:
                try:
                    message = base64.b64decode(message)
                except:
                    pass

            return message

        def clean(self):
            data = self.cleaned_data
            date = data.get('date') or datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
            return {'first': {'value': data['heading']
                         },
               'keyword1': {'value': self.decode_message(data['message'], data['is_message_base64'])
                            },
               'keyword2': {'value': date
                            },
               'remark': {'value': data.get('remark', '')
                          }
               }

    def handle(self):
        self.wx_template_id = getattr(self, 'wx_template_id', '') or getattr(configs, 'wx_template_id', '')
        self.wx_app_id = getattr(self, 'wx_app_id', '') or getattr(configs, 'wx_app_id', '')
        self.wx_secret = getattr(self, 'wx_secret', '') or getattr(configs, 'wx_secret', '')
        data = self.form_data
        data.update({'appid': self.wx_app_id,
           'secret': self.wx_secret,
           'template_id': self.wx_template_id,
           'url': self.request.kwargs.get('url', '')
           })
        self.response.payload = self.invoke_other('generic.weixin_mp.send_msg_with_tpl', kwargs=data)
